package service

import (
	"context"
	"fmt"
	"log"
	rand2 "math/rand"
	"strconv"
	"time"
	"user-rpc/basic/config"
	__ "user-rpc/basic/proto"
	"user-rpc/handler/model"
	"user-rpc/pkg"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	__.UnimplementedUserServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) Greet(_ context.Context, in *__.StreamReq) (*__.StreamResp, error) {
	log.Printf("Received: %v", in.GetName())
	return &__.StreamResp{}, nil
}

func (s *Server) SendSms(_ context.Context, in *__.SendSmsReq) (*__.SendSmsResp, error) {
	log.Printf("Received: %v", in.ProtoReflect())

	code := rand2.Intn(9000) + 1000
	sms, err := pkg.SendSms(in.UserName, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}
	if sms.Code != 2 {
		return nil, fmt.Errorf("短信发送失败")
	}
	config.Rdb.Set(config.Ctx, "SendSms"+in.UserName, code, time.Minute*5)
	return &__.SendSmsResp{}, nil
}

func (s *Server) Register(_ context.Context, in *__.RegisterReq) (*__.RegisterResp, error) {
	log.Printf("Received: %v", in.ProtoReflect())
	var err error
	count, _ := config.Rdb.Get(config.Ctx, "SendSms"+in.UserName).Result()
	if count != in.SmsSend {
		return nil, fmt.Errorf("验证码验证失败,请重试")
	}
	user := model.User{
		UserName:  in.UserName,
		Password:  pkg.Md5(in.Password),
		AvatarUrL: in.AvatarUrL,
		Status:    in.Status,
	}
	err = user.IsUser(config.DB, in.UserName)
	if err != nil {
		return nil, fmt.Errorf("用户已存在")
	}
	err = user.Register(config.DB)
	if err != nil {
		return nil, fmt.Errorf("注册失败")
	}

	return &__.RegisterResp{
		UserId: int64(user.ID),
	}, nil
}
func (s *Server) Login(_ context.Context, in *__.LoginReq) (*__.LoginResp, error) {
	log.Printf("Received: %v", in.ProtoReflect())
	var err error
	user := model.User{}
	err = user.IsUser(config.DB, in.UserName)
	if err != nil {
		return nil, err
	}
	if pkg.Md5(in.Password) != user.Password {
		return nil, fmt.Errorf("密码不正确")
	}
	token, err := pkg.GetJwtToken(strconv.Itoa(int(user.ID)))
	if err != nil {
		return nil, err
	}
	return &__.LoginResp{
		UserId: int64(user.ID),
		Data:   token,
	}, nil
}
